<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <%
        pageContext.setAttribute("APP",request.getContextPath());
    %>
    <link href="${APP}/Static-Resource/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="${APP}/Static-Resource/jquery-3.4.1.js"></script>
    <script src="${APP}/Static-Resource/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
    <title>Title</title>
</head>
<body>
<%--栅格搭建显示页面--%>
<div class="container">
    <%--    标题--%>
    <div class="row">
        <div class="col-md-12">
            <h1>SSM CUID</h1>
        </div>
    </div>
    <%--    新增和删除按钮--%>
    <div class="row">
        <div class="col-md-4 col-md-offset-8">
            <button class="btn btn-info" data-toggle="modal" data-target="#myModal" id="add_btn">新增</button>
            <button class="btn btn-danger " id="btn-delete-all">删除</button>
        </div>
    </div>
    <%--    显示项目表格--%>
    <div class="row">
        <div class="col-md-12">
            <table class="table table-hover" id="emps_table">
                <thead>
                    <tr>
                        <th>
                            <input type="checkbox" id="check-all">
                        </th>
                        <th>id</th>
                        <th>empName</th>
                        <th>gender</th>
                        <th>email</th>
                        <th>deptName</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>

                </tbody>

            </table>
        </div>
    </div>
    <%--    显示分页信息--%>
    <div class="row">
        <div class="col-md-6" id="pageInfo_area">

        </div>

        <div class="col-md-6">
            <nav aria-label="Page navigation">
                <ul class="pagination" id="nav_area">

                </ul>
            </nav>
        </div>
    </div>
</div>


<!--                          新增      模态框                                                   -->
<div class="modal fade" id="add_Modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">新增员工</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <div class="form-group">
                        <label for="add_inputName" class="col-sm-2 control-label">员工姓名</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="add_inputName" placeholder="富察·傅恒" name="empName" value="叶赫那拉·雨薇">
                            <span id="helpBlock1" class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="add_inputEmail" class="col-sm-2 control-label">电子邮箱</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="add_inputEmail" placeholder="my@cygnus.com" name="email" value="weier@cythia.com">
                            <span id="helpBlock2" class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="add_inputName" class="col-sm-2 control-label">性别</label>
                        <label class="radio-inline">
                            <input type="radio" name="gendar" id="add_man" value="M" > 男
                        </label>
                        <label class="radio-inline">
                            <input type="radio" name="gendar" id="add_woman" value="F" checked="checked"> 女
                        </label>
                    </div>
                    <div class="form-group">
                        <label for="add_inputName" class="col-sm-2 control-label">所在部门</label>
                        <div class="col-sm-4">
                            <select class="form-control" id="add_dept_select" name="dId">

                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="emp_save_btn">保存</button>
            </div>
        </div>
    </div>
</div>


<!--                          修改      模态框                                                   -->
<div class="modal fade" id="update_Modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel2">修改员工信息</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <div class="form-group">
                        <label for="add_inputName" class="col-sm-2 control-label">员工姓名</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="update_inputName" placeholder="富察·傅恒" name="empName" >
                            <span id="helpBlock3" class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="add_inputEmail" class="col-sm-2 control-label">电子邮箱</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="update_inputEmail" placeholder="my@cygnus.com" name="email" >
                            <span id="helpBlock4" class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="add_inputName" class="col-sm-2 control-label">性别</label>
                        <label class="radio-inline">
                            <input type="radio" name="gendar" id="update_man" value="M" > 男
                        </label>
                        <label class="radio-inline">
                            <input type="radio" name="gendar" id="update_woman" value="F" > 女
                        </label>
                    </div>
                    <div class="form-group">
                        <label for="add_inputName" class="col-sm-2 control-label">所在部门</label>
                        <div class="col-sm-4">
                            <select class="form-control" id="update_dept_select" name="dId">

                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="emp_update_btn">更新</button>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">

    // 页面加载完成瞬间发送AJAX请求拿到分页的数据
    //jQuery入口函数，直接调用抽取的skipPage
    $(function () {
        //去首页
        skipPage(1)
    })
//                                          渲染表格
    function build_table(result) {
        // 先清空上一次的页面元素
        $("#emps_table tbody").empty()

        var emps=result.extend.pageInfo.list
        $.each(emps,function (index,item) {
            var checkboxTd=$("<td><input type='checkbox' class='checkboxes'/></td>")
            var empIdTd=$("<td></td>").append(item.empId)
            var empNameTd=$("<td></td>").append(item.empName)
            var gendarTd=$("<td></td>").append(item.gendar=='M'?"男":"女")
            var emailTd=$("<td></td>").append(item.email)
            var deptNameTd=$("<td></td>").append(item.department.deptName)
            var editBtn=$("<button></button>").addClass("btn btn-primary btn-sm edit-btn")
                .append($("<span></span>").addClass("glyphicon glyphicon-pencil delete-btn"))
                .append("编辑")
            editBtn.attr("empID",item.empId)
            var delBtn=$("<button></button>").addClass("btn btn btn-danger btn-sm btn-delete")
                .append($("<span></span>").addClass("glyphicon glyphicon-trash"))
                .append("删除")
            delBtn.attr("empID",item.empId)
            var BtnTd=$("<td></td>").append(editBtn).append(" ").append(delBtn)

            $("<tr></tr>").append(checkboxTd).append(empIdTd).append(empNameTd)
                .append(gendarTd).append(emailTd).append(deptNameTd)
                .append(BtnTd)
                .appendTo("#emps_table tbody")
        });
    }
//                                      渲染分页栏

    //                                  分页信息栏
    function build_nav(result) {
        $("#pageInfo_area").empty()
        $("#pageInfo_area").append("当前第"+result.extend.pageInfo.pageNum+
            "页，共 "+result.extend.pageInfo.pages+" 页，"+result.extend.pageInfo.total+" 条记录")

    }
    //                                  分页导航栏
    function build_pageInfo(result) {

        //totalRecord全局属性。在方法中，前头加var就只能得到个局部变量
        totalRecord=result.extend.pageInfo.total
        currentPage=result.extend.pageInfo.pageNum

        $("#nav_area").empty()
        var ul=$("#nav_area")

        var first=$("<li></li>").append($("<a></a>").append("首页").attr("href","#"))

        var pre=$("<li></li>").append($("<a></a>").append("&laquo;"))
        if (result.extend.pageInfo.hasPreviousPage==false){
            pre.addClass("disabled")
            first.addClass("disabled")
        }
        else {
            first.click(function () {
                skipPage(1)
            })
            pre.click(function () {
                skipPage(result.extend.pageInfo.prePage)
            })
        }

        ul.append(first).append(pre)

        $.each(result.extend.pageInfo.navigatepageNums,function (index,item) {
            var pages=$("<li></li>").append($("<a></a>").append(item))
            if (result.extend.pageInfo.pageNum==item){
                pages.addClass("active")
            }
            pages.click(function () {
                skipPage(item)
            })
            ul.append(pages)
        })
        var next=$("<li></li>").append($("<a></a>").append("&raquo;"))
        var last=$("<li></li>").append($("<a></a>").append("末页").attr("href","#"))
        if (result.extend.pageInfo.hasNextPage==false){
            next.addClass("disabled")
            last.addClass("disabled")
        }
        else {
            next.click(function () {
                skipPage(result.extend.pageInfo.nextPage)
            })
            last.click(function () {
                skipPage(result.extend.pageInfo.pages)
            })
        }
        ul.append(next).append(last)
    }

//                                    查         逻辑
    function skipPage(pn) {
        $.ajax({
            url:"${APP}/empsj",
            //发给服务器的数据
            data:"pageNum="+pn,
            type:"GET",
            success:function (result) {
                console.log(result)
                build_table(result)
                build_pageInfo(result)
                build_nav(result)

            }
        })
    }



//                                        增        逻辑
        // 点击新增按钮
        $("#add_btn").click(function () {
            //每次点击新增按钮都要重置表单内之前的数据
            $("#add_Modal form")[0].reset()
            //再重置校验样式
            $("#add_Modal form").find("*").removeClass("has-success has-error")
            $("#add_Modal form").find(".help-block").text("")

            // 先发出一个AJAX请求查询部门信息显示在下拉列表中
            getDepts("#add_Modal select")
            // 在模态框弹出之前
            $('#add_Modal').modal()
        })
    //得到部门列表
    function getDepts(elem) {
        $(elem).empty()
        $.ajax({
            url:"${APP}/depts",
            type:"GET",
            success:function (result) {
                console.log(result)
                $(elem).append()
                $.each(result.extend.departments,function () {
                    var option=$("<option></option>").append(this.deptName).attr("value",this.deptId)
                    option.appendTo(elem)
                })
            }
        })
    }


    //                                 保存新增员工
    //                                      校验
    //                   前端校验, 主要用正则规范格式，真校验（比如查重）还得看后端
    function validate_add_form(){
        // 1.拿到要校验的数据，使用正则表达式
        var Name= $("#add_inputName").val()
        var regName=/(^[a-zA-Z0-9_-]{6,15}$)|(^[\u4e00-\u9fa5·]{2,10})/
        if (!regName.test(Name)){
            // alert("用户名必须是6到15位英文数字组合或2到10位中文")
            show_validateMessage("#add_inputName","error","用户名必须是6到15位英文数字组合或2到10位中文")
            return false
        }
        else {
            show_validateMessage("#add_inputName","success","用户名可以使用")
        }
        var Email= $("#add_inputEmail").val()
        var regName=/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
        if (!regName.test(Email)){
            // alert("邮箱格式不正确")
            show_validateMessage("#add_inputEmail","error","邮箱格式不正确")
            return false
        }
        else {
            show_validateMessage("#add_inputEmail","success","邮箱可以使用")
        }
        return true
    }
//              抽取显示校验信息的函数
    function show_validateMessage(elem,status,msg){
        //每次显示信息前总要移除之前的状态和信息
        $(elem).parent().removeClass("has-success has-error")
        $(elem).next().text("")

        if (status=="success") {
            $(elem).parent().addClass("has-success")
            $(elem).next("span").text(msg)
        }
        else if (status == "error"){
            $(elem).parent().addClass("has-error")
            $(elem).next("span").text(msg)
        }
    }
    //                                  AJAX后端校验
    //当文本框内容发生改变时，触发事件，发送ajax请求
    $("#add_inputName").change(function () {
        var empName=this.value
        $.ajax({
            url:"${APP}/validateName",
            data:"empName="+empName,
            type:"POST",
            success:function (result) {
                if (result.code==666){
                    show_validateMessage("#add_inputName","success",result.extend.matches_msg)
                    //给按钮添加属性别添错人了
                    $("#emp_save_btn").attr("back-validate","success")
                }
                else {
                    show_validateMessage("#add_inputName","error",result.extend.matches_msg)
                    $("#emp_save_btn").attr("back-validate","error")
                }
            }
        })
    })
    $("#add_inputEmail").change(function () {
        var email=this.value
        $.ajax({
            url:"${APP}/validateEmail",
            data:"email="+email,
            type:"POST",
            success:function (result) {
                if (result.code==666){
                    show_validateMessage("#add_inputEmail","success",result.extend.matches_msg)
                    //给按钮添加属性别添错人了
                    $("#emp_save_btn").attr("back-validate","success")
                }
                else {
                    show_validateMessage("#add_inputEmail","error",result.extend.matches_msg)
                    $("#emp_save_btn").attr("back-validate","error")
                }
            }
        })
    })
    
//                                      增    业务逻辑

    $("#emp_save_btn").click(function () {
        // // 先AJAX后端校验,避免P27开头
        // if ($(this).attr("back-validate")=="error") {
        //     return false
        // }
        // // 前端校验
        // if(!validate_add_form()){
        //     return false
        // }

        // 干活，先序列化表单信息为KV键值对
        var form=$("#add_Modal form").serialize()
        //然后POST ajx请求通过 “道路” 传递过去
        $.ajax({
            url:"${APP}/empsj",
            type:"POST",
            data:form,
            success:function (result) {
                // 1.如果服务端后端校验成功
                // 2.关闭模态框
                // 3.跳转到添加后的末页看一下结果
                if (result.code==666){
                    $("#add_Modal").modal('hide')
                    skipPage(totalRecord)
                }
                else {
                    if (undefined!=result.extend.ErrorFields.email) {
                        show_validateMessage("#add_inputEmail","error",result.extend.ErrorFields.email)
                    }
                    if (undefined!=result.extend.ErrorFields.empName) {
                        show_validateMessage("#add_inputName","error",result.extend.ErrorFields.empName)
                    }

                }

            }
        })
    })


//                                  改   逻辑
$(document).on("click",".edit-btn",function () {
    //每次点击新增按钮都要重置表单内之前的数据
    $("#update_Modal form")[0].reset()
    //再重置校验样式
    $("#update_Modal form").find("*").removeClass("has-success has-error")
    $("#update_Modal form").find(".help-block").text("")

    // 查出部门信息，显示部门信息
    getDepts("#update_Modal select")
    //查出员工信息，显示员工信息
    getEmp($(this).attr("empID"))
    // 给更新按钮也传递当前员工的ID备用
    $("#emp_update_btn").attr("empID",$(this).attr("empID"))
    // 模态框弹出
    $('#update_Modal').modal()
})
//              员工信息回显    
function getEmp(id) {
    $.ajax({
        url:"${APP}/empsj/"+id,
        type:"GET",
        success:function (result) {
            var emp=result.extend.emp
            $("#update_inputName").val(emp.empName)
            $("#update_inputEmail").val(emp.email)
            $("#update_Modal input[name=gendar]").val([emp.gendar])
            $("#update_Modal select").val([emp.dId])
        }
    })
}    
//                  更新逻辑
$("#emp_update_btn").click(function () {
    // 干活，先序列化表单信息为KV键值对
    var form=$("#update_Modal form").serialize()
    //然后POST ajx请求通过 “道路” 传递过去
    $.ajax({
        url:"${APP}/empsj/"+$(this).attr("empID"),
        // type:"POST",
        // data:form+"&_method=PUT",
        //配置了HttpPutFormContentFilter，才可以直接发PUT请求
        type:"PUT",
        data:form,
        success:function (result) {
            if (result.code==444){
                if (undefined!=result.extend.ErrorFields.email) {
                    show_validateMessage("#update_inputEmail","error",result.extend.ErrorFields.email)
                    return false
                }
                if (undefined!=result.extend.ErrorFields.empName) {
                    show_validateMessage("#update_inputName","error",result.extend.ErrorFields.empName)
                    return false
                }
            }
            $("#update_Modal").modal('hide')
            skipPage(currentPage)
            }
        })
})



    //                                  删   逻辑
    //      单个删除
$(document).on("click",".btn-delete",function () {
    var empName=$(this).parents("tr").find("td:eq(2)").text()
    var empId=$(this).attr("empID")
    if (confirm("确认删除员工【"+empName+"】吗？")) {
        $.ajax({
            url:"${APP}/empsj/"+empId,
            type:"DELETE",
            success:function (result) {
                skipPage(currentPage)
            }
        })
    }
})
    //多个删除
    //checkboxes逻辑
$("#check-all").click(function () {
    $(this).prop("checked")
    $(".checkboxes").prop("checked",$(this).prop("checked"))
})
$(document).on("click",".checkboxes",function () {
    var silver= $(".checkboxes:checked").length==$(".checkboxes").length
    $("#check-all").prop("checked",silver)
})

    //按钮逻辑
$("#btn-delete-all").click(function () {
    var empNames=""
    var empIds=""
    $.each($(".checkboxes:checked"),function () {
        empNames+=$(this).parents("tr").find("td:eq(2)").text()+","
        empIds+=$(this).parents("tr").find("td:eq(1)").text()+"-"
    })
    empNames=empNames.substring(0,empNames.length-1)
    empIds=empIds.substring(0,empNames.length-1)
    if (confirm("确认删除员工【"+empNames+"】吗？")){
        $.ajax({
            url:"${APP}/empsj/"+empIds,
            type:"DELETE",
            success:function (result) {
                alert(result.msg)
                skipPage(currentPage)
            }
        })
    }
})
</script>



</body>
</html>
